<?php
/**
 * Created by PhpStorm.
 * User: 我想有个家
 * Date: 2019/8/28
 * Time: 16:14
 */

namespace App\Controller\admin;


use App\Model\Doc;
use App\Validate\DocValidate;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\RequestMapping;

/**
 * Class DocController
 * @package App\Controller\admin
 * @Controller(prefix="a/doc")
 * @Middleware(\App\Middleware\AdminMiddleware::class)
 */
class DocController extends AdminBase {

    /**
     * 列表
     * @return array
     * @RequestMapping(path="lists",methods="get")
     */
    public function getLists() {
        $type = $this->get('type');
        $size = pageSizeVerify($this->get('size'));
        $result = Doc::query()
            ->where('is_delete', 0)
            ->where('type', $type)
            ->select('id', 'title', 'is_delete', 'update_time')
            ->paginate($size);
        return success(paginate($result));
    }

    /**
     * 单个信息
     * @return array
     * @RequestMapping(path="info",methods="get")
     */
    public function getInfo() {
        $id = (int) $this->get('id');
        $result = Doc::query()
            ->where('id', $id)
            ->select('id', 'title', 'content')
            ->first();
        return $result ? success($result) : error('数据不存在');
    }

    /**
     * 添加
     * @return array
     * @RequestMapping(path="info",methods="post")
     */
    public function postInfo() {
        $validate = $this->di->get(DocValidate::class);
        $validate->check($validate->add());
        $param = [
            'title' => $this->body('title'),
            'content' => $this->body('content'),
            'type' => $this->body('type'),
        ];
        $res = Doc::query()->insertGetId($param);
        return $res ? success() : error();
    }

    /**
     * 编辑
     * @return array
     * @RequestMapping(path="info",methods="put")
     */
    public function putInfo() {
        $validate = $this->di->get(DocValidate::class);
        $validate->check($validate->edit());

        $id = (int) $this->body('id');
        $param['title'] = $this->body('title');
        $param['content'] = $this->body('content');

        Doc::query()->where('id', $id)->update($param);
        return success();
    }

    /**
     * 删除
     * @return array
     * @RequestMapping(path="info",methods="delete")
     */
    public function deleteInfo() {
        $id = (int) $this->body('id');
        Doc::query()->where('id', $id)
            ->where('type', '<>', 2)
            ->update(['is_delete' => 1]);
        return success();
    }
}
